<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\MessageRequest;
use App\Models\Message;
use Illuminate\Http\Request;

class MessageController extends CommonController
{
    /**
     * 留言板管理后台留言列表
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Message::orderBy('id', 'desc')->paginate(3);
        return view('admin.message.index', compact('data'));
    }

    /**
     * 留言板管理后台新增留言
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * 留言板管理后台插入留言
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * 留言板管理后台查看留言
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 留言板管理后台编辑留言
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $field = Message::find($id);
        return view('admin.message.edit', compact('field'));
    }

    /**
     * 留言板管理后台修改留言
     * Update the specified resource in storage.
     *
     * @param MessageRequest $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(MessageRequest $request, $id)
    {
        $inputs = $request->except('_token', '_method');
        $result = Message::where('id', $id)->update($inputs);
        if ($result) {
            return redirect('admin/message');
        } else {
            return redirect()->back()->withErrors(['error'=> '编辑失败']);
        }
    }

    /**
     * 留言板管理后台删除留言
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $result = Message::where('id', $id)->delete();
        if ($result) {
            $data = [
                'status' => 0,
                'message' => '文章删除成功!',
            ];
        } else {
            $data = [
                'status' => 1,
                'message' => '文章删除失败，请稍后重试!',
            ];
        }
        return $data;
    }
}
